﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Rhizome.Contract;
using Rhizome.Contract.Diag;
using Rhizome.Model.Validation;

namespace Rhizome.Model
{
	public class ActiveTimerTrigger : ActiveTriggerBase<object>
	{
		/// <summary>
		/// 	The time interval between trigger will be trigged
		/// </summary>
		public TimeSpan Period { get; set; }

		#region Overrides of ActiveRuleBase<TPlant>

		protected override sealed IEnumerator Steps()
		{
			var ms = (int) Period.TotalMilliseconds;
			while (true)
			{
				Sleep(ms);
				yield return null;
				Trigged();
			}
		}

		#endregion

		#region validation

		public override IEnumerable<IValidationResult> GetValidationResults()
		{
			if (Period <= TimeSpan.Zero)
				return base.GetValidationResults().Concat(new[] {ValidationResult.Error("Period must be >= 0")});

			return base.GetValidationResults();
		}

		#endregion
	}
}